﻿CREATE PROCEDURE [dbo].[PartyGoodsDelete]
	@PartyId [int],
	@SetNoCount [bit]
WITH EXECUTE AS CALLER
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intRowCount int
DECLARE @strBarCode char(12), @intGoodsDocLinesId int, @intDocId int 
	SET NOCOUNT ON
IF 0 != 
(
SELECT TOP 1 DepartmentId FROM PR.DepartmentOptions
)
	BEGIN
		SET @strMsg = 'Накладные можно менять только в Оффисе  !'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END

IF (@PartyId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @strBarCode = P.BarCode, @intDocId = P.DocID, @intGoodsDocLinesId = L.Id
FROM CD.Parties P INNER JOIN CA.GoodsDocLines L
ON L.PartyId = P.Id AND L.DocId = P.DocId 
WHERE P.Id = @PartyId
IF (@@rowcount <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 206, 
	@strMsg = 'Партия с идентификатором ' + cast(@PartyId as varchar(20)) + ' не существует!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

--проверка товародвижения по приходу
IF EXISTS (SELECT Id FROM CA.GoodsDocLines WHERE PartyId = @PartyId AND DocId <> @intDocId)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 207, 
	@strMsg = 'По партии ' + @strBarCode + '(' + cast(@PartyId as varchar(20)) + ') было товародвижение!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

DELETE FROM [CA].[GoodsDocLines] WHERE Id = @intGoodsDocLinesId
SELECT @intRowCount = @@rowcount, @intErrCode = @@error
IF (@intErrCode <> 0)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	RETURN @intErrCode
END
IF (@intRowCount <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 208, 
	@strMsg = 'Строка товародвижения не удалена!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @SetNoCount = 0 SET NOCOUNT OFF

DELETE FROM CD.Parties WHERE Id = @PartyId
SELECT @intRowCount = @@rowcount, @intErrCode = @@error
IF (@intErrCode <> 0)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	RETURN @intErrCode
END
IF (@intRowCount <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 209, 
	@strMsg = 'Партия ' + @strBarCode + '(' + cast(@PartyId as varchar(20)) + ') не удалена!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

RETURN 0
